//
//  AllAddressViewController.m
//  JiuLe
//
//  Created by SunChao on 16/10/24.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "AllAddressViewController.h"
#import "AllAddressCell.h"
#import "MallRequestManager.h"
#import "AddressViewController.h"
#import "AddressViewController.h"
#define kCellReuseId  (@"addressCellId")
@interface AllAddressViewController ()

@end

@implementation AllAddressViewController
- (void)viewWillAppear:(BOOL)animated
{
    [self reloadAddressData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"管理收货地址";
    [self showNavgationWithLeftItemWithTitle:@""];
    [self showNavBarWithRightImage:[UIImage imageNamed:@"icon_add"] andRightBtnAction:@selector(addNewAddress)];
    [self.tableView registerNib:[UINib nibWithNibName:@"AllAddressCell" bundle:nil] forCellReuseIdentifier:kCellReuseId];
}
- (void)addNewAddress
{
    AddressViewController *address = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"address"];
    address.flag = 0;
    [self.navigationController pushViewController:address animated:YES];
}
- (void)reloadUI
{
    [self.tableView reloadData];
    NSMutableDictionary *dic = [NSMutableDictionary new];
    [dic setObject:self.dataSource forKey:@"address"];
    [[NSNotificationCenter defaultCenter]postNotificationName:addressReloadData object:nil userInfo:dic];
}
- (void)reloadAddressData
{
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:userId forKey:@"user_id"];
    [params setValue:token forKey:@"token"];
    [SVProgressHUD showWithStatus:@"加载中.." maskType:SVProgressHUDMaskTypeClear];
    [MallRequestManager post:Queryreceivingaddress RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [SVProgressHUD dismiss];
        if (connectionError) {
            NSLog(@"connectionError:%@",connectionError);
        }else
        {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//转换数据格式
            if ([dic.allKeys containsObject:@"result"]) {
                NSArray *result = [dic objectForKey:@"result"];
                self.dataSource = [NSMutableArray new];
                for (NSDictionary *dic in result) {
                    [self.dataSource addObject:[AddressModel appWithDict:dic]];
                }
                [self performSelectorOnMainThread:@selector(reloadUI) withObject:nil waitUntilDone:NO];
            }
        }
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AllAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellReuseId];

    if (cell ==nil) {
        cell = [[AllAddressCell alloc]init];
    }
    AddressModel *model = self.dataSource[indexPath.section];
    if (indexPath.section ==0) {
        cell.defaultAddressBtn.selected =YES;
    }else
    {
        cell.defaultAddressBtn.selected = NO;
    }
    [cell.defaultAddressBtn addTarget:self action:@selector(defaultAddressBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell.editorBtn addTarget:self action:@selector(editBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    cell.editorBtn.tag = indexPath.section+100;
    cell.defaultAddressBtn.tag = indexPath.section +200;
    cell.model = model;
    return cell;
}
//设置默认收货地址
- (void)defaultAddressBtnClicked:(UIButton *)sender{
    
    
    for (int i = 0; i<self.dataSource.count; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:i];
       AllAddressCell *cell =  [self.tableView cellForRowAtIndexPath:indexPath];
        cell.defaultAddressBtn.selected = NO;
    }
    //设置收货地址默认值
    NSMutableDictionary *params = [NSMutableDictionary new];
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    [params setValue:userId forKey:@"user_id"];
    [params setValue:token forKey:@"token"];
    AddressModel *model = [self.dataSource objectAtIndex:sender.tag-200];
    [params setObject:model.uid  forKey:@"address_id"];
    [MallRequestManager post:Setdefaultaddress RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [SVProgressHUD dismiss];
        if (connectionError) {
            NSLog(@"connectionError:%@",connectionError);
        }else
        {
            
        }
    }];

    sender.selected =YES;
    
}
//收货地址编辑
- (void)editBtnClicked:(UIButton *)sender {
    
     AddressModel *model = [self.dataSource objectAtIndex:sender.tag-100];
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setObject:model forKey:@"address"];
    //跳转收货地址编辑
    AddressViewController *address = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"address"];
    address.userInfo = [NSMutableDictionary new];
    address.userInfo = dict;
    address.flag = 1;
    [self.navigationController pushViewController:address animated:YES];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AddressModel *model =  [self.dataSource objectAtIndex:indexPath.section];
    NSMutableDictionary *dic = [NSMutableDictionary new];
    [dic setObject:model forKey:@"newAddress"];
    [[NSNotificationCenter defaultCenter]postNotificationName:changeAddressNoti object:nil userInfo:dic];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)dealloc
{
    NSLog(@"changeAddressNoti通知被移除");
    [[NSNotificationCenter defaultCenter]removeObserver:self name:changeAddressNoti object:nil];
}
/*屏蔽侧滑删除
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        删除收货地址 ShoppingMall/deletereceivingaddress
        NSMutableDictionary *params = [NSMutableDictionary new];
        NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
        NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
        AddressModel *model = self.dataSource[indexPath.section];
        NSString *addressId = model.uid;
        [params setObject:userId forKey:@"user_id"];
        [params setObject:token forKey:@"token"];
        [params setObject:addressId forKey:@"address_id"];
        
        [MallRequestManager post:@"ShoppingMall/deletereceivingaddress" RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (connectionError) {
                [SVProgressHUD showErrorWithStatus:@"删除失败"];
            }else
            {
                [SVProgressHUD showSuccessWithStatus:@"删除成功"];
                [self reloadAddressData];
            }
        }];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        
    }
}
*/
@end
